<template>
  <div>
    <Form
      ref="formData"
      :model="formData"
      :rules="formDataRules"
      :label-width="140"
    >
      <Card title="编辑资质" dis-hover class="ivu-mt">
        <Row>
          <Col span="18" offset="2">
            <FormItem label="资质名称" prop="qualificationName">
              <span>{{ formData.qualificationName }}</span>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="检验类型" prop="qualificationName">
              <RadioGroup v-model="formData.examineCate">
                <Radio label="1" disabled>全检</Radio>
                <Radio label="2" disabled>抽检</Radio>
                <Radio label="3" disabled>通用</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="是否原件" prop="qualificationName">
              <RadioGroup v-model="formData.original">
                <Radio label="1" disabled>是</Radio>
                <Radio label="2" disabled>否</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="资质类型" prop="qualificationName">
              <RadioGroup
                v-model="formData.qualificationCate"
                style="width: 200px"
                @on-change="radioChange($event)"
              >
                <Radio
                  disabled
                  :label="item.quaTypeNo"
                  :value="item.quaTypeNo"
                  v-for="(item, index) in quaTypeProductData"
                  :key="index"
                >
                  <span>{{ item.quaTypeName }}</span>
                </Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="供应商" prop="qualificationName">
              <Input
                v-model="formData.supplyName"
                style="width: 200px"
                placeholder="请输入供应商"
                search
                suffix="ios-search"
                @on-search="searcheSupply"
                readonly
              />
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="使用区域" prop="qualificationName">
              {{ formData.appliedAreaName }}
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="过期时间" prop="qualificationName">
              <DatePicker
                disabled
                type="date"
                v-model="formData.expireDate"
                format="yyyy-MM-dd HH:mm:ss"
                @on-change="changeStatTime($event)"
                placeholder="请选择时间"
              />
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="上传附件">
              <!-- <Upload ref="uploadFile" action="/sysback/fileserver/uploadfile" name="myfile"
              :on-success="handleFileSuccess" :before-upload="handleBeforeFileUpload">
              <Button icon="ios-cloud-upload-outline">点击上传</Button>
            </Upload> -->
              <div v-if="formData.annex">
                <Button icon="ios-cloud-download-outline" @click="onPreView"
                  >下载附件</Button
                >
              </div>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="上传图片">
              <UploadImg
                class="ivu-mr qw-disflex"
                :defaultList="defaultList"
                :mr="16"
                :maxSize="2048"
                :maxLen="5"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey"
                :readOnly="myState"
              >
              </UploadImg>
              <p>提示: 上传图片大小不能超过2048K,尺寸750px*360px</p>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="介绍">
              <span>{{ formData.note }}</span>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="">
              <Button @click="goBack" class="ivu-ml">返回</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
    </Form>
    <Modal v-model="modal1" title="选择区域" @on-ok="" @on-cancel="">
      <Tree
        ref="cityTree"
        :data="treeCityData"
        show-checkbox
        multiple
        @on-check-change="checkCityChange"
      />
    </Modal>
    <Modal title="预览图片" v-model="visible">
      <img :src="imageUrl" v-if="visible" style="width: 100%" />
    </Modal>
    <Modal
      v-model="supplierMainModel"
      width="1000"
      title="供应商列表"
      @on-ok=""
      @on-cancel=""
    >
      <Card dis-hover>
        <Row type="flex" justify="start" align="bottom">
          <Col style="margin-right: 40px">
            <span style="margin-right: 10px">供应商名称</span>
            <Input
              style="width: auto"
              v-model="supplierName"
              placeholder="请输入供应商名称"
            ></Input>
          </Col>
          <Col style="margin-right: 40px">
            <span style="margin-right: 10px">供应商编号</span>
            <Input
              style="width: auto"
              v-model="supplierNo"
              placeholder="请输入供应商编号"
            ></Input>
          </Col>
          <Col>
            <Button
              type="primary"
              style="margin-right: 10px"
              @click="searchBySupplierFun('1')"
              >查询</Button
            >
            <Button @click="searchBySupplierFun('0')">清空</Button>
          </Col>
        </Row>
      </Card>
      <Card dis-hover>
        <div>
          <div class="mt-10">
            <Table
              ref="selection"
              border
              :columns="supplierMainCol"
              :data="supplierMainData"
              @on-select="handleTablaeSelect($event)"
              @on-select-all="handleSelectAll($event)"
              @on-select-all-cancel="handleSelectAllCancel($event)"
            >
              <template slot-scope="{ div, index }" slot="action">
                <Button type="primary" @click="selectSupplier(row)"
                  >选择</Button
                >
              </template>
            </Table>
          </div>
          <div style="display: flex; justify-content: center">
            <Page
              :total="totalNum"
              show-total
              show-elevator
              show-sizer
              transfer
              @on-change="changePage"
              @on-page-size-change="changePageSize"
            />
          </div>
        </div>
      </Card>
    </Modal>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { cityTreeDataUtils } from '@/assets/js/commonUtils';
import UploadImg from '@/components/common/upload'; // 上传组件
export default {
  components: { UploadImg },
  data () {
    return {
      supplierName: '', // 供应商名称搜索用
      supplierNo: '', // 供应商编码搜索用
      supplierMainModel: false,
      totalPage: 0,
      pageShow: 10,
      nowPage: 1,
      myState: true,
      supplierMainCol: [
        // {
        //   type: 'selection',
        //   width: 60,
        //   align: 'center'
        // },
        {
          title: '供应商名称',
          key: 'supplierName',
          minWidth: 150
        },
        {
          title: '供应商编码',
          key: 'supplierNo',
          minWidth: 150
        },
        {
          title: '供应商状态',
          key: 'supplierStatusName'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          minWidth: 150
        }
      ],
      supplierMainData: [],
      quaTypeProductData: [],
      totalNum: 0,
      nowPage: 1,
      upLoadData: {
        categoryUuid: '111000'
      },
      fileCon: {
        type: 'select', // 上传控件的类型，可选值为 select（点击选择），drag（支持拖拽）
        showUploadList: true,
        multiple: false, // 是否支持多选文件
        format: ['jpg', 'jpeg', 'png'], // 支持的文件类型
        maxSize: 2048, // 文件大小限制，单位 kb Number
        maxLen: '3' // 文件数量限制
      },
      fileData: [],
      imageUrl: '',
      visible: false,
      uploadList: [],
      uploadFileList: [],
      rLoading: false,
      defaultList: [],
      // 请求接口地址
      requestApi: {
        // 视情况自定义
        // 获取商品资质管理列表数据
        baseUpdate: {
          url: '/sysback/qualification/baseUpdate', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 获取商品资质管理数据
        baseGetByUuid: {
          url: '/sysback/qualification/baseGetByUuid', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 主推城市
        getCityTree: {
          url: '/sysback/addsingleproduct/basicinfo/getCityTree',
          type: 'post'
        },
        // 获取供应商列表
        getPagerSupplierMainInfo: {
          url: '/sysback/supplier/maininfo/list/getPotentialOrQualifiedSupplierPager',
          type: 'post'
        },
        // 查询商品资质类型
        quaTypeProductList: {
          url: '/sysback/quatype/quaTypeProductList',
          type: 'post'
        }
      },
      modal1: false,
      treeCityData: [],
      brandList: [],
      salableAreaData: [],
      areaNames: [],
      cityUuids: [],
      productDetailImages: [], // 图片回显
      formData: {
        qualificationName: '', // 资质名称
        examineCate: '1', // 检验类型 默认 1 全检
        original: '1', // 是否原件
        qualificationCate: '1', // 资质类型
        qualificationCateName: '', // 资质类型名称
        supplyName: '', // 供应商名称
        supplyUuid: '', // 供应商Uuid
        supplyNo: '', // 供应商编码
        appliedArea: '', // 使用区域–JSON
        appliedAreaName: '', // 使用区域
        expireDate: '', // 过期时间
        annex: '', // 附件地址
        imageKey: '', // 图片地址，英文逗号拼接
        imageKey2: '', // 图片地址，英文逗号拼接
        imageKey3: '', // 图片地址，英文逗号拼接
        imageKey4: '', // 图片地址，英文逗号拼接
        imageKey5: '', // 图片地址，英文逗号拼接
        enable: '1', // 是否启用
        note: '' // 说明--介绍
      },
      formDataRules: {
        qualificationName: [{ required: true, message: ' ', trigger: 'blur' }]
      }
    };
  },
  created () {
    this.getCityTree();
    this.quaTypeProductList();
    this.getPagerSupplierMainInfo();
    this.uuid = this.$route.query.uuid;
    this.baseGetInfoByUuid();
  },
  mounted () {
    this.uploadFileList = this.$refs.uploadFile.fileList;
  },
  methods: {
    changeImageKey (imgArr) {
      switch (imgArr.length) {
        case 1:
          this.formData.imageKey = imgArr[0].response.retData;
          break;
        case 2:
          this.formData.imageKey = imgArr[0].response.retData;
          this.formData.imageKey2 = imgArr[1].response.retData;
          break;
        case 3:
          this.formData.imageKey = imgArr[0].response.retData;
          this.formData.imageKey2 = imgArr[1].response.retData;
          this.formData.imageKey3 = imgArr[2].response.retData;
          break;
        case 4:
          this.formData.imageKey = imgArr[0].response.retData;
          this.formData.imageKey2 = imgArr[1].response.retData;
          this.formData.imageKey3 = imgArr[2].response.retData;
          this.formData.imageKey4 = imgArr[3].response.retData;
          break;
        case 5:
          this.formData.imageKey = imgArr[0].response.retData;
          this.formData.imageKey2 = imgArr[1].response.retData;
          this.formData.imageKey3 = imgArr[2].response.retData;
          this.formData.imageKey4 = imgArr[3].response.retData;
          this.formData.imageKey5 = imgArr[4].response.retData;
          break;
      }
    },
    baseGetInfoByUuid () {
      // 开始请求列表
      this.rLoading = true;
      ApiRequest(
        this.requestApi.baseGetByUuid.url,
        this.requestApi.baseGetByUuid.type,
        { uuid: this.uuid },
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let retData = res.retData;
          this.formData = {
            qualificationName: retData.qualificationName, // 资质名称
            examineCate: retData.examineCate.toString(), // 检验类型 默认 1 全检
            original: retData.original, // 是否原件
            qualificationCate: retData.qualificationCate, // 资质类型
            qualificationCateName: retData.qualificationCateName,
            supplyName: retData.supplyName, // 供应商名称
            supplyUuid: retData.supplyUuid, // 供应商Uuid
            appliedArea: retData.appliedArea, // 使用区域–JSON
            appliedAreaName: retData.appliedAreaName,
            expireDate: retData.expireDate, // 过期时间
            annex: retData.annex, // 附件地址
            imageList: retData.imageList,
            // imageKey: retData.imageKey, // 图片地址，英文逗号拼接
            // imageKey2:  retData.imageKey2, // 图片地址，英文逗号拼接
            // imageKey3:  retData.imageKey3, // 图片地址，英文逗号拼接
            // imageKey4:  retData.imageKey4, // 图片地址，英文逗号拼接
            // imageKey5: retData.imageKey5, // 图片地址，英文逗号拼接
            enable: retData.enable ? '1' : '2', // 是否启用
            note: retData.note // 说明--介绍
          };
          retData.imageList.forEach((item) => {
            let obj = {};
            obj.url = '/' + item.attachmentUrl;
            this.defaultList.push(obj);
          });
          this.uploadFileList.push({
            name: '已上传附件',
            url: this.formData.annex
          });
          this.$forceUpdate();
        }
        this.rLoading = false;
      });
    },
    searchBySupplierFun (type) {
      if (type === '0') {
        this.supplierName = '';
        this.supplierNo = '';
      } else {
        this.getPagerSupplierMainInfo();
      }
    },
    // 获取供应商列表
    getPagerSupplierMainInfo () {
      let searchParam = [];
      searchParam.push({ name: 'supplierName', value: this.supplierName });
      searchParam.push({ name: 'supplierName_q', value: 'Like' });
      searchParam.push({ name: 'supplierNo', value: this.supplierNo });
      searchParam.push({ name: 'supplierNo_q', value: 'EQ' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };
      // 开始请求列表
      ApiRequest(
        this.requestApi.getPagerSupplierMainInfo.url,
        this.requestApi.getPagerSupplierMainInfo.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.supplierMainData = res.retData.results;
          this.totalNum = res.retData.totalNum;
        }
      });
    },
    // 获取资质类型
    quaTypeProductList () {
      let data = {};
      // 开始请求列表
      ApiRequest(
        this.requestApi.quaTypeProductList.url,
        this.requestApi.quaTypeProductList.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.quaTypeProductData = res.retData;
        }
      });
    },
    // 预览/下载文件
    onPreView (file) {
      window.location.href =
        this.exportBaseURL +
        '/sysback/fileserver/download/' +
        this.formData.annex;
    },
    // 选择供货商
    selectSupplier (row) {
      this.formData.supplyName = row.supplierName;
      this.formData.supplyUuid = row.uuid;
      this.formData.supplyNo = row.supplierNo;
      this.supplierMainModel = false;
      this.$forceUpdate();
    },
    // 单选监听
    radioChange (data) {
      this.quaTypeProductData.forEach((element) => {
        if (data === element.quaTypeNo) {
          this.formData.qualificationCateName = element.quaTypeName;
        }
      });
    },
    changeStatTime (val) {
      this.formData.expireDate = val;
    },
    handleFileSuccess (res, file) {
      this.formData.annex = res.retData;
    },
    handleBeforeFileUpload () {
      const check = this.uploadFileList.length < 1;
      if (!check) {
        this.$Notice.warning({
          title: '上传文件达到最大限制.'
        });
      }
      return check;
    },
    // 城市选择
    checkCityChange () {
      let sdata = this.$refs.cityTree.getCheckedNodes();
      this.formData.appliedArea = '';
      this.formData.appliedAreaName = '';
      sdata.forEach((item) => {
        if (item.children == undefined) {
          this.formData.appliedArea += item.code + ',';
          this.formData.appliedAreaName += item.title + ',';
        }
      });
    },
    // 获取城市树
    getCityTree () {
      let data = {};
      // 开始请求列表
      ApiRequest(
        this.requestApi.getCityTree.url,
        this.requestApi.getCityTree.type,
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.treeCityData = cityTreeDataUtils(res.retData);
        }
      });
    },
    // 打开可售区域
    salableAreaHandle () {
      this.modal1 = true;
      if (this.cityUuids.length > 0) {
        this.cityUuids.forEach((item) => {
          let itemArr = item.split('-');
          for (let i = 0; i < this.salableAreaData.length; i++) {
            let fData = this.salableAreaData[i];
            if (fData.value === itemArr[0]) {
              if (itemArr[1] === 'ALL') {
                fData.checked = true;
                fData.children.forEach((obj) => {
                  obj.checked = true;
                });
              } else {
                fData.children.forEach((obj) => {
                  if (obj.value === itemArr[1]) {
                    obj.checked = true;
                  }
                });
              }
              return;
            }
          }
        });
      }
      this.areaDrawerShow = true;
    },
    // 商品详情图片
    changeDetailImage (imgArr) {},
    toRelease (formData) {
      if (
        this.formData.qualificationName === undefined ||
        this.formData.qualificationName === null ||
        this.formData.qualificationName === ''
      ) {
        this.$Message.error('资质名称不能为空!');
        return;
      }
      if (
        this.formData.examineCate === undefined ||
        this.formData.examineCate === null ||
        this.formData.examineCate === ''
      ) {
        this.$Message.error('检验类型不能为空!');
        return;
      }
      if (
        this.formData.original === undefined ||
        this.formData.original === null ||
        this.formData.original === ''
      ) {
        this.$Message.error('是否原件不能为空!');
        return;
      }
      if (
        this.formData.qualificationCate === undefined ||
        this.formData.qualificationCate === null ||
        this.formData.qualificationCate === ''
      ) {
        this.$Message.error('资质类型不能为空!');
        return;
      }
      if (
        this.formData.supplyName === undefined ||
        this.formData.supplyName === null ||
        this.formData.supplyName === ''
      ) {
        this.$Message.error('供应商不能为空!');
        return;
      }
      if (
        this.formData.appliedArea === undefined ||
        this.formData.appliedArea === null ||
        this.formData.appliedArea === ''
      ) {
        this.$Message.error('使用区域不能为空!');
        return;
      }
      if (
        this.formData.expireDate === undefined ||
        this.formData.expireDate === null ||
        this.formData.expireDate === ''
      ) {
        this.$Message.error('过期时间不能为空!');
        return;
      }
      this.formData.expireDate = this.changeDate(this.formData.expireDate);
      this.formData.uuid = this.uuid;
      let copyData = Object.assign({}, formData);
      // 开始请求列表
      this.rLoading = true;
      ApiRequest(
        this.requestApi.baseUpdate.url,
        this.requestApi.baseUpdate.type,
        copyData
      )
        .then((res) => {
          if (res.retStatus === '1') {
            this.$Message.success('修改资质成功!');
            this.$router.go(-1);
          }
          this.rLoading = false;
        })
        .catch((err) => {
          this.rLoading = false;
        });
    },
    // 时区日期格式转换(TZ)
    changeDate (myData) {
      var date1 = new Date(myData).toJSON();
      var date = new Date(+new Date(date1) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '');
      return date;
    },
    goBack () {
      this.$router.go(-1);
    },
    searcheSupply () {
      this.supplierMainModel = true;
    },
    handleTablaeSelect (data) {},
    handleSelectAll (data) {},
    handleSelectAllCancel (data) {},
    changePage (e) {
      this.nowPage = e;
      this.getPagerSupplierMainInfo();
    },

    changePageSize (e) {
      this.pageShow = e;
      this.getPagerSupplierMainInfo();
    }
  }
};
</script>
<style lang="less" scoped>
.mt-10 {
  margin-bottom: 10px;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
